package org.jeecg.modules.online.desform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.es.JeecgElasticsearchTemplate;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.desform.constant.DesformConstant;
import org.jeecg.modules.online.desform.constant.WidgetTypes;
import org.jeecg.modules.online.desform.entity.DesignForm;
import org.jeecg.modules.online.desform.entity.DesignFormData;
import org.jeecg.modules.online.desform.mapper.DesignFormDataMapper;
import org.jeecg.modules.online.desform.mapper.DesignFormMapper;
import org.jeecg.modules.online.desform.service.IDesignFormDataService;
import org.jeecg.modules.online.desform.service.IDesignFormService;
import org.jeecg.modules.online.desform.util.DesformUtils;
import org.jeecg.modules.online.desform.util.FormDataUtil;
import org.jeecg.modules.online.desform.vo.TranslateData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 表单设计
 * @Author: jeecg-boot
 * @Date: 2019-05-16
 * @Version: V1.0
 */
@Slf4j
@Service("designFormServiceImpl")
public class DesignFormServiceImpl extends ServiceImpl<DesignFormMapper, DesignForm> implements IDesignFormService {

	@Autowired
	private DesignFormMapper designFormMapper;
	@Autowired
	private DesignFormDataMapper designFormDataMapper;
	@Autowired
	private IDesignFormDataService dataService;
	@Autowired
	private ISysBaseAPI sysBaseApi;

	@Autowired
	private JeecgElasticsearchTemplate jes;

    @Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(DesignForm designForm) {
		/* 填充默认值 */

		// 表单类型默认为主表
		if(oConvertUtils.isEmpty(designForm.getDesformType())){
			designForm.setDesformType(DesformConstant.DESFORM_TYPE_MV);
		}

        // 异步创建 ElasticSearch 索引
        DesformUtils.asyncCreateEsIndex(designForm.getDesformCode());

		designFormMapper.insert(designForm);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(DesignForm designForm, List<DesignFormData> designFormDataList) {
		designFormMapper.updateById(designForm);

		// 1.先删除子表数据
		designFormDataMapper.deleteByMainId(designForm.getId());

		// 2.子表数据重新插入
		for (DesignFormData entity : designFormDataList) {
			// 外键设置
			entity.setDesformId(designForm.getId());
			designFormDataMapper.insert(entity);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
        DesignForm designForm = baseMapper.selectById(id);
        if (designForm != null) {
            designFormDataMapper.deleteByMainId(designForm.getId());
            designFormMapper.deleteById(designForm.getId());
            // 异步删除 ElasticSearch 索引
            DesformUtils.asyncRemoveEsIndex(designForm.getDesformCode());
        }
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
        List<DesignForm> list = baseMapper.selectList(new LambdaQueryWrapper<DesignForm>().in(DesignForm::getId, idList));
		for (DesignForm designForm : list) {
			designFormDataMapper.deleteByMainId(designForm.getId());
			designFormMapper.deleteById(designForm.getId());
            // 异步删除 ElasticSearch 索引
			DesformUtils.asyncRemoveEsIndex(designForm.getDesformCode());
        }
	}

	@Override
	public DesignForm getByCode(String desformCode) {
		LambdaQueryWrapper<DesignForm> queryWrapper = new LambdaQueryWrapper<DesignForm>();
		queryWrapper.eq(DesignForm::getDesformCode, desformCode);

		// 首先查询出表单配置json
		DesignForm designForm = baseMapper.selectOne(queryWrapper);
		return designForm;
	}

	@Override
	public ModelAndView queryFormViewData(DesignForm designForm, String dataId, String onlineDataId, ModelAndView modelAndView) {
		// 首先查询出表单配置json
		if (designForm == null) {
			throw new JeecgBootException("表单设计不存在！");
		}
		modelAndView.addObject("designForm", queryAllDictItem(designForm));

		// 再判断是否为新增
		if (!"add".equals(dataId)) {
			DesignFormData designFormData = null;
            //update-begin--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------
			//1.判断表数据ID onlineDataId不为空，则优先走通过表获取逻辑
			if(org.apache.commons.lang.StringUtil.isNotEmpty(onlineDataId)){
                String tbname = null;
				//通过online对应表查询数据库
                String desformDesignStr = designForm.getDesformDesignJson();
                if(oConvertUtils.isNotEmpty(desformDesignStr)){
                    JSONObject json = JSONObject.parseObject(desformDesignStr);
                    if(json.get("config")!=null){
                        JSONObject config = (JSONObject) json.get("config");
                        if(config.get("onlineForm")!=null){
                            tbname = (String) config.get("onlineForm");
                        }
                    }
                }
                if(StringUtil.isNotEmpty(tbname)){
                    Map<String,Object> dataMap = designFormDataMapper.queryOneByTableNameAndId(tbname,onlineDataId);
					if (dataMap == null) {
						throw new JeecgBootException("表单数据不存在！");
					}
                    String subTables = designFormDataMapper.getSubTablesByTableName(tbname);
                    designFormData = new DesignFormData();
                    //判断是否主子表，是的话，把关联子表数据也查询出来
                    if(StringUtil.isNotEmpty(subTables)){
                        for(String sub:subTables.split(",")){
                            String deString = null;
                            try {
                                deString = URLEncoder.encode("[{}]", "UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            dataMap.put("sub-table-design_"+sub,deString);
                        }
                    }

                    //此处判断如果是oracle数据库，则把map数据库key转成小写
                    try {
                        String dbType = CommonUtils.getDatabaseType();
                        if(DataBaseConstant.DB_TYPE_ORACLE.equalsIgnoreCase(dbType)){
                            designFormData.setDesformDataJson(JSONObject.toJSONString(FormDataUtil.transLowerCaseMapKey(dataMap)));
                        }else{
                            designFormData.setDesformDataJson(JSONObject.toJSONString(dataMap));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        designFormData.setDesformDataJson(JSONObject.toJSONString(dataMap));
                    }
                    designFormData.setDesformId(designForm.getId());
                    designFormData.setDesformCode(designForm.getDesformCode());
                    designFormData.setDesformName(designForm.getDesformName());
                    designFormData.setOnlineFormCode(tbname);
                    designFormData.setOnlineFormDataId(onlineDataId);

                    //update-begin--Author:zhangdaihao  Date:20201106 for：解决online配置设计器表单，可以同步变更设计表单中间表数据-----
                    //设置表单设计器数据的ID design_form_data
                    LambdaQueryWrapper<DesignFormData> queryWrapper=new LambdaQueryWrapper<DesignFormData>();
                    queryWrapper.eq(DesignFormData::getOnlineFormDataId,onlineDataId);
                    queryWrapper.eq(DesignFormData::getDesformId,designForm.getId());
                    DesignFormData mp = designFormDataMapper.selectOne(queryWrapper);
                    if (mp != null) {
                        designFormData.setId(mp.getId());
                    }else{
                        designFormData.setId("ONLINE-DATA-TEMP-ID");
                    }
                    //update-end--Author:zhangdaihao  Date:20201106 for：解决online配置设计器表单，可以同步变更设计表单中间表数据-----
                }
			}else{
			    //2.判断表数据库ID为空，则通过表单设计器data中获取数据
				designFormData = designFormDataMapper.selectById(dataId);
			}
            //update-end--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------
			if (designFormData == null) {
				throw new JeecgBootException("表单数据不存在，dataId="+dataId);
			}
			modelAndView.addObject("designFormData", designFormData);
			if(designFormData!=null){
                log.debug(" designFormData: "+ designFormData.toString());
            }
		}

		return modelAndView;
	}

	@Override
	public ModelAndView queryFormViewById(String desformId, String dataId, String onlineDataId, ModelAndView modelAndView) {
		// 首先查询出表单配置json
		DesignForm designForm = this.getById(desformId);
		return this.queryFormViewData(designForm, dataId,onlineDataId, modelAndView);
	}

	@Override
	public ModelAndView queryFormViewByCode(String desformCode, String dataId, String onlineDataId, ModelAndView modelAndView) {
		return this.queryFormViewByCode(desformCode, dataId, onlineDataId, false, modelAndView);
	}

	/**
	 * 查询表单浏览页面的数据（自动判断是否有移动端视图，有的话就走移动端视图）
	 *
	 * @param desformCode
	 * @param dataId  表单设计数据json的数据ID
	 * @param onlineDataId  online表数据ID
	 * @param modelAndView
	 * @return
	 */
    @Override
    public ModelAndView queryFormAutoViewByCode(String desformCode, String dataId, String onlineDataId, ModelAndView modelAndView) {
	    // 查询出表单配置和所有的视图
        LambdaQueryWrapper<DesignForm> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignForm::getParentCode, desformCode);
        queryWrapper.eq(DesignForm::getIzMobileView, DesformConstant.IS_MOBILE_VIEW_Y);

		List<DesignForm> designFormList = super.list(queryWrapper);
		//移动视图模板
		DesignForm mobileForm = null;
		if (designFormList.size() > 0) {
			// 循环判断是否有移动端视图
			mobileForm = designFormList.get(0);
		} else {
			mobileForm = this.getByCode(desformCode);
		}
		if (mobileForm == null) {
			throw new JeecgBootException("表单设计不存在！");
		}
		return this.queryFormViewData(mobileForm, dataId, onlineDataId, modelAndView);
    }

    @Override
	public ModelAndView queryFormViewByCode(String desformCode, String dataId, String onlineDataId, boolean isExternal, ModelAndView modelAndView) {
		// 首先查询出表单配置json
		DesignForm designForm = this.getByCode(desformCode);
		if (designForm != null && isExternal) {
			JSONObject json = JSON.parseObject(designForm.getDesformDesignJson());
			JSONObject config = json.getJSONObject("config");
			boolean allowExternalLink = config.getBooleanValue("allowExternalLink");
			// 判断是否允许打开外部链接
			if (!allowExternalLink) {
				throw new JeecgBootException("已禁止访问此链接");
			}
		}
		return this.queryFormViewData(designForm, dataId,onlineDataId, modelAndView);
	}

	/**
	 * 判断是否是字典类型，如果是就查询字典
	 */
	@Override
	public DesignForm queryAllDictItem(DesignForm designForm) {
		String designJson = (String) designForm.getDesformDesignJson();
		if (StringUtils.isEmpty(designJson)) {
			return designForm;
		}

		JSONObject json = JSONObject.parseObject(designJson);
		JSONArray list = json.getJSONArray("list");
		for (int i = 0; i < list.size(); i++) {
			JSONObject item = list.getJSONObject(i);
			String type = item.getString("type");
			// 判断是否是 栅格布局 或 子表
			if ("grid".equals(type) || "sub-table-design".equals(type)) {
				JSONArray columns = item.getJSONArray("columns");
				for (int j = 0; j < columns.size(); j++) {
					JSONArray columnList = columns.getJSONObject(j).getJSONArray("list");
					for (int k = 0; k < columnList.size(); k++) {
						this.ifCurrentIsSelect(columnList.getJSONObject(k));
					}
				}
			} else {
				this.ifCurrentIsSelect(item);
			}
		}
		designForm.setDesformDesignJson(json.toJSONString());

		return designForm;
	}

	/** 判断当前项是否为select */
	private void ifCurrentIsSelect(JSONObject item) {
		String type = item.getString("type");
		if ("select".equals(type)) {
			JSONArray selectOptions = this.queryDictOptions(item);
			if (selectOptions != null) {
				JSONObject options = item.getJSONObject("options");
				options.put("remote", false);
				options.put("showLabel", true);
				options.put("options", selectOptions);
			}
		}
	}

	/** 查询字典数据 */
	private JSONArray queryDictOptions(JSONObject item) {
		try {
			JSONObject options = item.getJSONObject("options");
			String remote = options.getString("remote");
			// 判断是否为字典类型
			if ("dict".equals(remote)) {
				String dictCode = options.getString("dictCode");
				// 封装
				List<DictModel> dictItems = sysBaseApi.queryDictItemsByCode(dictCode);
				JSONArray selectOptions = new JSONArray();
				for (DictModel dictModel : dictItems) {
					JSONObject option = new JSONObject();
					option.put("label", dictModel.getText());
					option.put("value", dictModel.getValue());
					selectOptions.add(option);
				}
				return selectOptions;

			}
		} catch (org.springframework.data.redis.serializer.SerializationException e) {
			// do nothing
		}
		return null;
	}


    /**
     * 普通同步索引（分页）
     * 只更新索引的文档
     */
    @Override
    public Result redoAllIndex(String rowIds, Integer pageSize, boolean batchSave) {
        if (pageSize == null) {
            return this.redoPageIndex(rowIds, null, null, batchSave);
        } else {
            return this.redoPageIndex(rowIds, 1, pageSize, batchSave);
        }
    }

    // 可递归调用的快速分页重置
    private Result redoPageIndex(String rowIds, Integer pageNum, Integer pageSize, boolean batchSave) {
        try {
            long begin = System.currentTimeMillis();
            log.info("-- 已开始快速重置ES索引数据");
            LambdaQueryWrapper<DesignFormData> queryWrapper = new LambdaQueryWrapper<DesignFormData>();
            if (oConvertUtils.isNotEmpty(rowIds)) {
                queryWrapper.in(DesignFormData::getDesformId, Arrays.asList(rowIds.split(",")));
            }
            List<DesignFormData> dataList;
            Page<DesignFormData> pageList = null;
            if (pageNum == null || pageSize == null) {
                dataList = dataService.list(queryWrapper);
            } else {
                batchSave = true;
                pageList = dataService.page(new Page<>(pageNum, pageSize), queryWrapper);
                dataList = pageList.getRecords();
                log.info("-- 快速分页重置：（第 " + (pageList.getCurrent()) + " 页/共 " + pageList.getPages() + " 页）");
            }

            int successCount = 0, failCount = 0;
            if (!batchSave) {
                for (int i = 0; i < dataList.size(); i++) {
                    DesignFormData dataItem = dataList.get(i);
                    String desformCode = dataItem.getDesformCode();
                    log.info("---- 正在重置：" + desformCode + "（第 " + (i + 1) + " 个/共 " + dataList.size() + " 个）");
                    JSONObject dataJson = JSON.parseObject(dataItem.getDesformDataJson());
                    if (jes.saveOrUpdate(desformCode, "design_form", dataItem.getId(), dataJson)) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                }
            } else {
                Map<String, JSONArray> saveMap = new HashMap<>();
                for (DesignFormData dataItem : dataList) {
                    String desformCode = dataItem.getDesformCode();
                    JSONObject dataJson = JSON.parseObject(dataItem.getDesformDataJson());
                    dataJson.put("id", dataItem.getId());
                    JSONArray saveDataList = saveMap.computeIfAbsent(desformCode, k -> new JSONArray());
                    saveDataList.add(dataJson);
                }
                for (String desformCode : saveMap.keySet()) {
                    JSONArray saveDataList = saveMap.get(desformCode);
                    log.info("---- 正在批量重置：" + desformCode + "（共 " + saveDataList.size() + " 条数据）");
                    jes.saveBatch(desformCode, "design_form", saveDataList);
                }
            }
            long end = System.currentTimeMillis();
            String msg;
            if (failCount == 0) {
                msg = "快速重置ES索引全部成功!";
            } else {
                msg = String.format("快速重置ES索引：成功了%s条，失败了%s条", successCount, failCount);
            }
            log.info("-- " + msg);
            log.info("-- 总耗时：" + (end - begin) + " ms");
            if (pageList != null && pageList.hasNext()) {
                return this.redoPageIndex(rowIds, ++pageNum, pageSize, batchSave);
            } else {
                return Result.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 强制同步索引
     * 删除索引重新创建，并同步索引文档
     */
    @Override
    public Result redoAllIndexForce(String rowIds, Integer pageSize) {
        try {
            log.info("-- 已开始强制重置ES索引");
            LambdaQueryWrapper<DesignForm> queryWrapper = new LambdaQueryWrapper<DesignForm>();
            if (oConvertUtils.isNotEmpty(rowIds)) {
                queryWrapper.in(DesignForm::getId, Arrays.asList(rowIds.split(",")));
            }
            List<DesignForm> allForm = super.list(queryWrapper);
            long begin = System.currentTimeMillis();
            for (int i = 0; i < allForm.size(); i++) {
                DesignForm formItem = allForm.get(i);
                String desformCode = formItem.getDesformCode();
                log.info("---- 正在重置：" + desformCode + "（第 " + (i + 1) + " 个/共 " + allForm.size() + " 个）");
                jes.removeIndex(desformCode);
                jes.createIndex(desformCode);
            }
            long end = System.currentTimeMillis();
			log.info("-- 强制重置ES索引完成，即将开始快速重置数据");
            log.info("-- 总耗时：" + (end - begin) + " ms");
            return this.redoAllIndex(rowIds, pageSize, true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDefMobileViewStatus(String parentCode, String desformCode) {
        DesignForm updateEntity = new DesignForm();
        QueryWrapper<DesignForm> updateWrapper = new QueryWrapper<>();
        // 去掉其他的移动模板
        updateEntity.setIzMobileView(DesformConstant.IS_MOBILE_VIEW_N);
        updateWrapper.eq("iz_mobile_view", DesformConstant.IS_MOBILE_VIEW_Y).eq("desform_code", parentCode).or().eq("parent_code", parentCode);
        super.update(updateEntity, updateWrapper);
        // 设置新的移动模板
        updateEntity.setIzMobileView(DesformConstant.IS_MOBILE_VIEW_Y);
        updateWrapper = new QueryWrapper<DesignForm>().eq("desform_code", desformCode);
        super.update(updateEntity, updateWrapper);
        return true;
    }

    @Override
    public Map<String, List<DictModel>> translateColumns(List<TranslateData> translateDataList) {
        Map<String, List<DictModel>> translateMap = new HashMap<>();
        // 待翻译的用户数据
        List<TranslateData> userTransDataList = new ArrayList<>();
        // 待翻译的部门数据
        List<TranslateData> departDataList = new ArrayList<>();
        for (TranslateData transItem : translateDataList) {
            // 判断翻译类型
            WidgetTypes type = transItem.getType();
            String customReturnField = transItem.getCustomReturnField();
            if (type == WidgetTypes.SELECT_USER) {
                // 翻译用户组件
                userTransDataList.add(transItem);
            } else if (type == WidgetTypes.SELECT_DEPART) {
                // 翻译部门组件
                departDataList.add(transItem);
            }
        }
        //update-begin--Author:zhangdaihao  Date:20200819 for：陶炎微服务壳子模式，底层API重构 / JT-302【设计器bug】列表展示，部门组件未翻译-------------------
        // 查询并翻译出所有的用户信息
        if (userTransDataList.size() > 0) {
//            QueryWrapper userQueryWrapper = this.getTranslateQueryWrapperByCustomReturnField(userTransDataList);
//            log.info("userQueryWrapper: ",userQueryWrapper.toString());
//            List<JSONObject> userQueryList = sysBaseApi.queryAllUser(userQueryWrapper);
            String customReturnField = userTransDataList.get(0).getCustomReturnField();
            String usernames = getTranslateValsByCustomReturnField(userTransDataList);
            List<JSONObject> userQueryList = null;
            //自定义返回字段（目前只针对 id、username做翻译）
            if("id".equals(customReturnField)){
                userQueryList = sysBaseApi.queryUsersByIds(usernames);
            }else if("username".equals(customReturnField)){
                userQueryList = sysBaseApi.queryUsersByIds(usernames);
            }
            log.info("usernames: "+ usernames);
            this.packageOptionsPutTranslateMap(translateMap, userTransDataList, userQueryList, "realname");
        }
        // 查询并翻译出所有的部门信息
        if (departDataList.size() > 0) {
//            QueryWrapper departQueryWrapper = this.getTranslateQueryWrapperByCustomReturnField(departDataList);
//            log.info("departQueryWrapper: ",departQueryWrapper.toString());
//            List<JSONObject> departQueryList = sysBaseApi.queryAllDepart(departQueryWrapper);
            //自定义返回字段（目前只针对 id、orgCode做翻译）
            String customReturnField = departDataList.get(0).getCustomReturnField();
            String orgIds = getTranslateValsByCustomReturnField(departDataList);
            log.info("orgIds: "+ orgIds);
            List<JSONObject> departQueryList = null;
            if("id".equals(customReturnField)){
                departQueryList = sysBaseApi.queryDepartsByIds(orgIds);
            }else if("orgCode".equals(customReturnField)){
                departQueryList = sysBaseApi.queryDepartsByOrgcodes(orgIds);
            }

            this.packageOptionsPutTranslateMap(translateMap, departDataList, departQueryList, "departName");
        }
        //update-end--Author:zhangdaihao  Date:20200819 for：陶炎微服务壳子模式，底层API重构 / JT-302【设计器bug】列表展示，部门组件未翻译-------------
        return translateMap;
    }




    /**
     * 根据不同的 CustomReturnField 生成不同的 QueryWrapper
     *
     * @param transDataList
     * @return
     */
    private String getTranslateValsByCustomReturnField(List<TranslateData> transDataList) {
        Map<String, List<String>> inMap = new HashMap<>();
        for (TranslateData transItem : transDataList) {
            String customReturnField = transItem.getCustomReturnField();
            List<String> list = inMap.computeIfAbsent(customReturnField, k -> new ArrayList<>());
            list.addAll(transItem.getDataList());
        }
        LinkedHashSet<String> vals = new LinkedHashSet();
        for (String key : inMap.keySet()) {
            vals.addAll(inMap.get(key));
        }
        return StringUtils.join(vals.toArray(), ",");
    }

    /**
     * 根据不同的 CustomReturnField 生成不同的 QueryWrapper
     *
     * @param transDataList
     * @return
     */
    private QueryWrapper getTranslateQueryWrapperByCustomReturnField(List<TranslateData> transDataList) {
        QueryWrapper<?> queryWrapper = new QueryWrapper();
        Map<String, List<String>> inMap = new HashMap<>();
        for (TranslateData transItem : transDataList) {
            String customReturnField = transItem.getCustomReturnField();
            List<String> list = inMap.computeIfAbsent(customReturnField, k -> new ArrayList<>());
            list.addAll(transItem.getDataList());
        }
        for (String key : inMap.keySet()) {
            // 驼峰转下划线
            String inKey = oConvertUtils.camelToUnderline(key);
            queryWrapper.in(inKey, inMap.get(key)).or();
        }
        return queryWrapper;
    }

    /**
     * 将返回数据，包装成前台能识别的Options
     */
    private void packageOptionsPutTranslateMap(Map<String, List<DictModel>> translateMap, List<TranslateData> translateDataList, List<JSONObject> queryDataList, String textLabel) {
        for (TranslateData transItem : translateDataList) {
            for (String data : transItem.getDataList()) {
                for (JSONObject queryData : queryDataList) {
                    String value = queryData.getString(transItem.getCustomReturnField());
                    if (value != null && value.equals(data)) {
                        String text = queryData.getString(textLabel);
                        List<DictModel> list = translateMap.computeIfAbsent(transItem.getKey(), k -> new ArrayList<>());
                        list.add(new DictModel(value, text));
                        break;
                    }
                }
            }
        }
    }

}
